package com.jianli.smart.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.jianli.smart.core.annotation.Controller;
import com.jianli.smart.core.annotation.RequestMapping;
import com.jianli.smart.core.entity.Handler;
import com.jianli.smart.core.entity.Request;

public final class ControllerHelper {
	private static final Map<Request,Handler> SERVICE_MAP = new HashMap<Request,Handler>();
	
	static{
		// 获取所有controller
		Set<Class<?>> controllerSet = ClassHelper.getSet(Controller.class);
		
		if(controllerSet != null && !controllerSet.isEmpty()){
			for(Class<?> controllerClass:controllerSet){
				// 获取controller下定义的方法
				Method[] methods = controllerClass.getMethods();
				// 遍历方法下的requestMapper里的值
				if(methods != null && methods.length > 0){
					for(Method method:methods){
						if(method.isAnnotationPresent(RequestMapping.class)){
							// 获取映射规则，添加到SERVICE_MAP中：MAP的KEY为request，值为handler
							RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
							String requestValue = requestMapping.value();
							String requestMethod = requestMapping.method();
							Request request = new Request(requestMethod, requestValue);
							Handler handler = new Handler(controllerClass, method);
							SERVICE_MAP.put(request, handler);
						}
					}
				}
			}
		}
	}
	
	public static Handler getHandler(String requestMethod, String requestValue){
		Request request = new Request(requestMethod, requestValue);
		return SERVICE_MAP.get(request);
	}
}
